package cn.jinjimi.app.main.fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import bolts.Continuation;
import bolts.Task;
import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.DESEncryptUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.domain.data.dto.TokenDto;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.framework.helper.annotation.EventTraceParam;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.domain.data.net.ApiConstants;
import cn.jinjimi.app.bean.EventDataField;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.controller.UserController;
import cn.jinjimi.app.controller.event.DataEvent;
import cn.jinjimi.app.controller.event.LoginEvent;
import cn.jinjimi.app.controller.event.LoginSuccessEvent;
import cn.jinjimi.domain.data.dto.ProfileDTO;
import cn.jinjimi.framework.router.Router;
import cn.jinjimi.app.main.activity.LoginActivity;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.MTextWatcher;
import cn.jinjimi.app.main.widget.PhoneBaseEditTextView;
import cn.jinjimi.app.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 密码登陆
 * @author zhenhua
 */
public class LoginWithPswFragment extends BaseFragment implements View.OnClickListener {
    private PhoneBaseEditTextView phone;
    private Button cleanPhone;
    private EditText password;
    private Button cleanPassword;
    private TextView signIn;
    private View forgetPsw;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_loginwithpsw;
    }

    @Override
    protected void initial() {
        initView();
        initListener();

    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().setTitle(R.string.title_phone_psw_login);
    }

    protected void initView() {
        phone = (PhoneBaseEditTextView) findView().findViewById(R.id.et_phone);
        cleanPhone = (Button) findView().findViewById(R.id.bt_clean_phone_number);
        password = (EditText) findView().findViewById(R.id.et_password);
        cleanPassword = (Button) findView().findViewById(R.id.bt_clean_password);
        signIn = findView().findViewById(R.id.bt_sign_in);
        forgetPsw = findView().findViewById(R.id.forget_psw);
        cleanPhone.setVisibility(StringUtils.isEmpty(phone.getText().toString()) ? View.GONE : View.VISIBLE);
    }

    protected void initListener() {
        cleanPhone.setOnClickListener(this);
        cleanPassword.setOnClickListener(this);
        signIn.setOnClickListener(this);
        forgetPsw.setOnClickListener(this);
        phone.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    cleanPhone.setVisibility(View.VISIBLE);
                } else {
                    cleanPhone.setVisibility(View.INVISIBLE);
                }
            }
        });
        password.addTextChangedListener(new MTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    cleanPassword.setVisibility(View.VISIBLE);
                } else {
                    cleanPassword.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_clean_phone_number:
                resetMobile();
                break;
            case R.id.bt_clean_password:
                resetPassword();
                break;
            case R.id.bt_sign_in:
                doLogin();
                break;
            case R.id.forget_psw:
                toForgetPsw();
                break;
            default:break;
        }
    }

    private void resetMobile() {
        phone.setText("");
    }

    private void resetPassword() {
        password.setText("");
    }

    private void doLogin() {
        String mobile = phone.getRealPhoneNum();
        if (!checkPhoneNum(mobile)) {
            return;
        }
        String pwd = password.getText().toString().trim();
        if (!checkPasswordInput(pwd)) {
            return;
        }
        ((LoginActivity) getActivity()).showLoadingIndicator();
        UserController
                .loginById(mobile, pwd)
                .onSuccess(new Continuation<TokenDto, Void>() {
                    @Override
                    public Void then(Task<TokenDto> task) throws Exception {
                        ((LoginActivity) getActivity()).hideLoadingIndicator();
                        TokenDto dto = task.getResult();
                        if (task.isFaulted() || task.isCancelled() || dto == null) {
                            ToastUtils.toastMessage(getActivity(), getString(R.string.login_fail));
                        } else {
                            if (!TextUtils.isEmpty(dto.token)) {
                                onLoginSuccess(dto.token);
                            } else {
                                ToastUtils.toastMessage(getActivity(), dto.message);
                            }
                        }
                        return null;
                    }
                }, Task.UI_THREAD_EXECUTOR);
    }

    private void toForgetPsw() {
        FragmentManager fm = getActivity().getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.content_fragment, new ResetPswFragment(), "FORGETPSW");
        ft.addToBackStack(null);
        ft.commit();
    }

    private boolean checkPasswordInput(String pwd) {
        if (StringUtils.isEmpty(pwd)) {
            ToastUtils.toastMessage(getActivity(), R.string.input_u_password);
            return false;
        }
        return true;
    }

    private boolean checkPhoneNum(String mobile) {
        if (TextUtils.isEmpty(mobile)) {
            ToastUtils.toastMessage(getActivity(), cn.jinjimi.base.R.string.empty_phone);
            return false;
        }
        if (!StringUtils.isMobile(mobile)) {
            ToastUtils.toastMessage(getActivity(), cn.jinjimi.base.R.string.input_u_correct_phone);
        }
        return true;
    }

    private void onLoginSuccess(String token) {
        phone.savePhoneNum();
        AccountManager.getInstance().setToken(token);
        getActivity().finish();
    }

    @Override
    public void onPause() {
        super.onPause();
        AndroidUtils.hideSoftKeyBoard(getActivity(), phone);
    }
}
